package com.example.wificon;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.example.wificon.TargetList.GetTasksTask;
import comm.savagelook.android.UrlJsonAsyncTask;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ManageNetworks extends Activity {
	private static final String TASKS_URL = "http://10.0.2.2:3000/taskscomplete.json";
	private Button back;
	private Button exitButton;
	private Button settingsButton;
	private Button getTaskButton;
	private Button create;
	private PopupWindow pw;
	private View popupView;
	// GridView gridView;
	TableLayout tableView;

	/*
	 * static final String[] numbers = new String[] { "No",
	 * "Name of connection", "Password", "IP", "", "F", "G", "H", "I", "Edit",
	 * "K", "L", "M", "N", "Edit", "P", "Q", "R", "S", "Edit", "U", "V", "W",
	 * "X", "Edit"};
	 */
	static String[] numbers; /*= new String[] {
		"No", "Address", "Name ","Password", "IP", "",
		"1", "Address 1", "Connect to 1", "123","connect", "Edit", 
		"2", "Fondovi Jilishta", "Hrizantem4o", "321","fondo", "Edit",
		"3", "Florokompni", "leopard", "123", "kondo","Edit",
		"212", "Ulica Sezam", "kakadu", "321", "pongo", "Edit",
		"212", "Ulica Sezam", "kakadu", "321", "pongo", "Edit",
		"212","Ulica Sezam", "kakadu", "321", "pongo", "Edit",
		"212","Ulica Sezam", "kakadu", "321", "pongo", "Edit",
		"212","Ulica Sezam", "kakadu", "321", "pongo", "Edit",
		"212","Ulica Sezam", "kakadu", "321", "pongo", "Edit",
		"212","Ulica Sezam", "kakadu", "321", "pongo", "Edit", };*/

	@SuppressLint("InlinedApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manage_networks);
		loadTasksFromAPI(TASKS_URL);

		/*
		 * setContentView(R.layout.manage_networks);
		 * 
		 * gridView = (GridView) findViewById(R.id.manage_grid);
		 * 
		 * ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		 * android.R.layout.simple_list_item_1, numbers);
		 * 
		 * gridView.setAdapter(adapter);
		 * 
		 * gridView.setOnItemClickListener(new OnItemClickListener() { public
		 * void onItemClick(AdapterView<?> parent, View v, int position, long
		 * id) { Toast.makeText(getApplicationContext(), ((TextView)
		 * v).getText(), Toast.LENGTH_SHORT).show(); } });
		 */
		// TODO Auto-generated method stub

		back = (Button) findViewById(R.id.home_button_manage);

		back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		exitButton = (Button) findViewById(R.id.exit_button_manage);
		exitButton.setX(140);
		exitButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				System.exit(0);
			}
		});
		settingsButton = (Button) findViewById(R.id.settings_button_manage);
		settingsButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ChangeScreen("ACCOUNT_SETTINGS");
			}
		});
		getTaskButton = (Button) findViewById(R.id.view_tasks_manage); // not
																		// exatly
		getTaskButton.setX(140);
		getTaskButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ChangeScreen("TARGET_LIST");
			}
		});

		/*
		 * create = (Button) findViewById(R.id.create_button);
		 * create.setOnClickListener(new View.OnClickListener() {
		 * 
		 * @Override public void onClick(View arg0) { //check in data base
		 * information from the username and password ChangeScreen("CREATE"); }
		 * });
		 */

	}

	private void ChangeScreen(String intentName) {
		Intent changeScreen;
		changeScreen = new Intent("com.example.wificon." + intentName);
		startActivity(changeScreen);
	}

	public void onButtonInPopupCancel(View target) {
		pw.dismiss();
	}

	public void onButtonInPopupConfirm(View target) {
		EditText name = (EditText) popupView.findViewById(R.id.new_name_pop);
		EditText IP = (EditText) popupView.findViewById(R.id.new_id_pop);
		EditText pass = (EditText) popupView.findViewById(R.id.new_pass_pop);
		
		int position = Integer.parseInt(((TextView)popupView.findViewById(R.id.id_pop)).getText().toString().replaceAll(" ", ""));
		Log.i("position2", position + " ");
		setData(position, 2, name);
		setData(position, 3, pass);
		setData(position, 4, IP);
		pw.dismiss();
	}
	
	private void setData(int rowPosition, int position, TextView fromText)
	{
		TableRow row = (TableRow)tableView.getChildAt(rowPosition);
		TextView data = (TextView)row.getChildAt(position);
		data.setText(fromText.getText().toString());
		row = (TableRow)tableView.getChildAt(position);
		Log.i("data", data.getText().toString() + " ");
		//tableView.refreshDrawableState();
		//tableView.notify();
	}
	
	private void loadTasksFromAPI(String url) {
	    GetTasksTask getTasksTask = new GetTasksTask(ManageNetworks.this);
	    getTasksTask.setMessageLoading("Loading tasks...");
	    getTasksTask.execute(url);
	}

	private class GetTasksTask extends UrlJsonAsyncTask {
	    public GetTasksTask(Context context) {
	        super(context);
	    }

	    @Override
	        protected void onPostExecute(JSONObject json) {
	            try {
	            	int counter = 1;
	                JSONArray jsonTasks = json.getJSONObject("data").getJSONArray("tasks");
	                int length = jsonTasks.length();
	                numbers = new String[length];
	                for (int i = 0; i < length; i++) {
	                	if( counter % 6 == 0){
	                		numbers[i] = "Edit";
	                	}
	                	else{
	                		counter++;
		                	
		                	numbers[i] = jsonTasks.getJSONObject(i).getString("title");
	                	}
	                	
	                }
	               
	            } catch (Exception e) {
	            Toast.makeText(context, e.getMessage(),
	                Toast.LENGTH_LONG).show();
	        } finally {
	            super.onPostExecute(json);
	            generateTable();
	        }
	    }
	    private void generateTable(){
	    	try {
				int itemNumber = numbers.length;
				TextView[] tView = new TextView[itemNumber];
				int counter = 0;

				tableView = (TableLayout) findViewById(R.id.manage_table);
				Context context = ManageNetworks.this;

				final TableRow[] tableRow = new TableRow[itemNumber / 6];
				for (int j = 0; j < itemNumber / 6; j++) {
					tableRow[j] = new TableRow(context);
					for (int i = 0; i < 6; i++) {

						if (j != 0 && i == 5) {
							Button edit = new Button(context);
							edit.setText("Edit");
							edit.setId(j);
							edit.setOnClickListener(new Button.OnClickListener() {

								@SuppressLint("InlinedApi")
								@Override
								public void onClick(View arg0) {
									
									LayoutInflater inflater = (LayoutInflater) ManageNetworks.this
											.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
									popupView = inflater
											.inflate(
													R.layout.popup_window,
													(ViewGroup) findViewById(R.layout.manage_networks));

									pw = new PopupWindow(popupView,
											700,
											LayoutParams.WRAP_CONTENT, true);

									pw.setAnimationStyle(android.R.style.Animation_Dialog);
									pw.showAtLocation(findViewById(1),
											Gravity.CENTER, 0, 0);
									EditText name = (EditText) (popupView
											.findViewById(R.id.new_name_pop));
									EditText IP = (EditText) (popupView
											.findViewById(R.id.new_id_pop));
									EditText pass = (EditText) (popupView
											.findViewById(R.id.new_pass_pop));
									int position = arg0.getId();
									TextView idNum = (TextView) popupView
											.findViewById(R.id.id_pop);
									idNum.setText(position + " ");
									name.setText(((TextView)(tableRow[position].getChildAt(2))).getText().toString());
									pass.setText(((TextView)(tableRow[position].getChildAt(3))).getText().toString());
									IP.setText(((TextView)(tableRow[position].getChildAt(4))).getText().toString());
									Log.i("address",((TextView)(tableRow[position].getChildAt(1))).getText().toString());

									/*
									 * Runnable mUpdateTimeTask = new Runnable() {
									 * // class DismissPopup implements Runnable {
									 * public void run() { // Protect against
									 * null-pointer exceptions if (pw != null) {
									 * pw.dismiss(); } } };
									 */
									// mHandler.postDelayed(mUpdateTimeTask, 5000);

									// Button dismiss = (Button)
									// findViewById(R.id.dismiss);
									// dismiss.setOnClickListener(new
									// Button.OnClickListener() {

									// @Override
									// public void onClick(View arg0) {
									// pw.dismiss();
									// popup.
									// }
									// });

								}
							});

							tableRow[j].addView(edit);
							counter += 1;
						}

						else {
							tView[i] = new TextView(context);

							tView[i].setText(numbers[counter].toString());
							tView[i].setTextSize(10);
							counter += 1;

							tView[i].setTextColor(Color.rgb(100, 200, 200));
							tView[i].setGravity(0x11);
							if (i == 0) {
								tView[i].setWidth(80);
							} else {
								tView[i].setWidth(160);
								tView[i].setHeight(100);
							}
							tableRow[j].addView(tView[i]);
						}

					}

					tableView.addView(tableRow[j]);
				}
				tableView.setColumnShrinkable(1,true);
			} catch (Exception e) {
				Log.e("MainActivity", "Error in activity", e);
				Toast.makeText(getApplicationContext(),
						e.getClass().getName() + " " + e.getMessage(),
						Toast.LENGTH_LONG).show();
			}
	    }
	}	    
}
